<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2022/5/19
  Time: 23:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <font color="aqua" size="10">用户注册</font><br>
    用户名：<input type="text" name="username" id="username"/><br>
    <span id="sp"></span><br>
    密码：<input type="password" name="pwd" id="pwd"><br>
    <input type="button" value="注册" onclick="regist()"/>

    <script type="text/javascript">
        // /**
         function regist() {
            // 1. 获取input输入框的值
            var username = document.getElementById("username").value;

            //2. 进行验证, 输入的值不为null
            if (username != null && username != "")  {

                //3. 创建ajax对象
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    //浏览器是IE7+, firefox, chrome, sfari等
                    xmlhttp = new XMLHttpRequest();
                } else {
                    //浏览器是IE5或者IE6
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }

                //4. 设置监听, 监听返回的状态码
                xmlhttp.onreadystatechange = function(){
                    //readystate状态码为4代表请求完成, 响应已就绪,
                    //state状态码为200代表http请求成功
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                        //5. 获取响应的数据
                        var result = xmlhttp.responseText;

                        //6. 将返回的数据操作DOM填充到页面中显示
                        //获取id叫做sp的对象
                        var sp = document.getElementById("sp");
                        if (result == "1") {
                            //该用户可以注册
                            var html = "<font color='green'>恭喜您可以注册!</font>";
                            sp.innerHTML = html;
                        } else {
                            //该用户已经存在
                            var html = "<font color='red'>该用户已存在!</font>";
                            sp.innerHTML = html;
                        }
                    }
                }
                //7. 设置ajax的请求方式和请求路径 pageContext.request.contextPath
                xmlhttp.open("POST", "${pageContext.request.contextPath}/registServlet", true);

                //8. 设置ajax的请求头
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

                // 9. 发送请求
                xmlhttp.send("name="+username);
            }
        }


    </script>
</body>
</html>
